<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<title>角色管理</title>
		<meta name="renderer" content="webkit">
		<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
		<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
		<meta name="apple-mobile-web-app-status-bar-style" content="black">
		<meta name="apple-mobile-web-app-capable" content="yes">
		<meta name="format-detection" content="telephone=no">
		<link rel="stylesheet" href="./lib/layui/css/layui.css" media="all">
		<link rel="stylesheet" href="./css/xadmin.css" media="all">
		<script src="./js/global.js" type="text/javascript" charset="utf-8"></script>
		<script type="text/javascript" src="lib/layui/layui.js" ></script>
	</head>
	<body>
		  <div class="x-nav">
            <a class="layui-btn layui-btn-small" style="line-height:1.6em;margin-top:3px;float:right" onclick="location.reload()" title="刷新">
                <i class="layui-icon layui-icon-refresh" style="line-height:30px"></i>
            </a>
        </div>
		<!--树：设置权限-->
		<div id="tree" style="display: none;">
		<div id="test12"></div>
		<div style="text-align: center;">
		<button id="tj" class="layui-btn">确定</button>
		</div>
		</div>
		<!--添加div-->
		<div id="addDiv" style="display: none;">
			<form class="layui-form" lay-filter="addform" id="addform" style="margin-top: 20px;" onsubmit="return false">

				<div class="layui-form-item">
					<label class="layui-form-mid">职务：</label>
					<div class="layui-input-inline" style="width: 350px;">
						<input class="layui-input" name="name" />
					</div>
				</div>
				<div class="layui-form-item" style="width: 200px;">
					<div class="layui-input-block" style="width: 200px;">
						<button id="btnAdd" class="layui-btn" lay-filter="test" lay-submit>添加</button>
					</div>
				</div>
			</form>
		</div>

		<!--修改div-->
		<div id="UpdateDiv" style="display: none;">
			<form class="layui-form" lay-filter="Updateform" id="Updateform" style="margin-top: 20px;" onsubmit="return false">

				<div class="layui-form-item">
					<input type="hidden" name="id" id="id" />
					<label class="layui-form-mid">职务：</label>
					<div class="layui-input-inline" style="width: 350px;">
						<input class="layui-input" name="name" />
					</div>
				</div> 
				<div class="layui-form-item" style="width: 200px;">
					<div class="layui-input-block" style="width: 200px;">
						<button class="layui-btn" lay-submit lay-filter="update">修改</button>
					</div>
				</div>
			</form>
		</div>
		<div class="layui-fluid">
		<!--多条件查询-->
		<div id="pdiv">
			<form class="layui-form" lay-filter="pform" id="pform" style="margin-top: 20px;" onsubmit="return false">

					<label class="layui-form-mid">角色：</label>
					<div class="layui-input-inline" style="width: 150px;">
						<input class="layui-input" id="n" />
					</div>
				<div class="layui-input-inline" style="width:100px;">
					<button class="layui-btn" id="search" data-type="reload">搜索</button> 
				</div> 
			</form>
		</div>
		<!--表-->
		<table class="layui-hide" id="demo" lay-filter="table">
		</table>
		<!-- 头部工具栏 -->
		<script type="text/html" id="top">
			<button class="layui-btn" lay-event="add">添加</button>
		</script>

		<!-- 列工具栏--> 
		<script type="text/html" id="cz">
			<a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="shu"><i class="layui-icon">&#xe620;</i>设置权限</a>
			<button class="layui-btn layui-btn-xs" lay-event="update">修改</button>
			<button class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</button>
		</script>
		</div>
		<script type="text/javascript">
			var treeNodeid = null;
			var tree, layer, $, form;
			layui.use(['layer', 'laydate', 'table', 'form','tree'], function() {
			var table = layui.table;
			layer = layui.layer;
			var laydate = layui.laydate;
			form = layui.form;
			$ = layui.$;
			tree = layui.tree;

			table.render({
				elem: '#demo',
				url: globalData.server+'role/getAllRoles',
				where:{'token':globalData.getCurToken()},
				method: 'post',
				page: true,
				toolrow: true,
				toolbar: '#top',
				parseData: function(res) {
					return {
						"code": 0,
						"msg": "1",
						"count": res.totalElements,
						"data": res.content
					}
				},
				cols: [
					[{
							type:"numbers",
							title: '编号'
						},
						{
							field: 'name',
							title: '职务'
						},
						{
							title: '操作',
							toolbar: '#cz'
						}
					]
				],
				id: 'a'

			})
			active={
				reload:function(){
					var n=$("#n");
					table.reload("a",{
						where:{
						"token":globalData.getCurToken(),
						"name":n.val()
						}
						 
					})
				}
			}
			$("#search").on("click",function(){
					active.reload();
				});
			//监听添加按钮
			table.on("toolbar(table)", function(obj) {
				if(obj.event == "add") {
					
						layer.open({
						type: 1,
						title: '添加',
						content: $("#addDiv"),
						area: ['450px', '300px']
					})
					
					
				}

			})

			table.on('tool(table)', function(obj) {
				var data = obj.data;
				var id = data.id;
				if(obj.event == "update") {
					
						form.val('Updateform', obj.data);
					layer.open({
						type: 1,
						title: '修改'+data.name+"角色的信息",
						content: $("#UpdateDiv"),
						area: ['450px', '500px']
					})
					
					
				} else if(obj.event == "del") {
					
						layer.confirm('确定删除吗', function() {
						$.post(globalData.server+"role/delroles", {
							id: id,
							'token':globalData.getCurToken()
						}, function(res) {
							if(res > 0) {
								layer.msg("删除成功");
								active.reload();
							} else {
								layer.msg("删除失败，该角色有权限");
							}

							}, 'json')
						})
					
				}else if(obj.event == "shu"){
					
						//获取到角色原本有的权限，放到集合a中
					var a = [];
					var p=[];
					$.post(globalData.server + "per/getroleIdModulesz", {
						'token': globalData.getCurToken(),
						'id': data.id
					}, function(res) {
						$.each(res, function(j, val) {
							a.push(val.permissionid);
							p.push(val);
						});
					}, "json")
					//权限树
						$.post(globalData.server + "module/findAllModules1", {
						'token': globalData.getCurToken()
					}, function(res) {
						tree.render({
							elem: '#test12',
							data: res,
							showCheckbox: true, //是否显示复选框
							id: 'demoId1',
							accordion: true,
							oncheck: function(obj){
								if(obj.data.title!="查询" && obj.checked){
									if(!isInArray(a,obj.data.id)){
										$.post(globalData.server+"per/getIdByPer",{'token':globalData.getCurToken(),'parentid':obj.data.parentid},function(res){
											if(res!=null){
												for(var i=0;i<res.length;i++){
													if(res[i].permissionname=="查询"){
														tree.setChecked('demoId1',res[i].permissionid);
													}
												}
												
											}
										})
									}else{
										for (var i=0;i<p.length;i++) {
											if(obj.data.parentid==p[i].permissionmodule && p[i].permissionname=="查询"){
												tree.setChecked('demoId1',p[i].permissionid);
											}
										}
									}
								}else if(obj.data.title=="查询" && !obj.checked){
										$.post(globalData.server+"per/getIdByPer",{'token':globalData.getCurToken(),'parentid':obj.data.parentid},function(res){
											if(res!=null){
												for(var i=0;i<res.length;i++){
													tree.unsetChecked('demoId1',res[i].permissionid);
												}
												
											}
										})
								}
								
								
								
							}
						})
						treeNodeid=data.id;//角色id
						tree.setChecked('demoId1', a); //批量勾选 集合a中的id 的节点
					}, "json")
						
					layer.open({
						type: 1,
						title: '修改'+data.name+"角色的权限",
						content: $("#tree"),
						area:['450px', '300px']
					})
					
				}
			})

				form.on('submit(test)', function() {
				var data = $("#addform").serialize()+"&token="+globalData.getCurToken();
				$.post(globalData.server+'role/AddRoles', data, function(res) {
					if(res > 0) {
						layer.closeAll();
						layer.msg("添加成功！");
						active.reload();
					}else{
						layer.msg("添加失败，该角色已存在！");
					}
				}, "json")
			})

			form.on('submit(update)', function() {
				$.post(globalData.server+"role/Updateroles", $("#Updateform").serialize()+"&token="+globalData.getCurToken(), function(res) {
					if(res > 0) {
						layer.closeAll();
						layer.msg("修改成功！");
						active.reload();
					}else{
						layer.msg("修改失败，该角色已存在！");
					}
				}, "json")
			})
     //设置权限的提交按钮
    		 $("#tj").on("click",function(){
    		 	var checkData = tree.getChecked('demoId1');
						for(var i = 0; i < checkData.length; i++) {
							getChildrenId(checkData[i]);//调用递归的方法来获取所有选中节点的Id
							for (var j=0;j<checkData[i].children.length;j++) {
								getChildrenId1(checkData[i].children[j]); 
							}
							
						}
						console.log(checkData);
						console.log(arr);
						console.log(b);
						$.post(globalData.server + "role/delRolesModules", {
							'rid': treeNodeid,
							"modulesid": arr.join(","),
							"permissionid":b.join(","),
							'token': globalData.getCurToken()
						}, function(res) {
							if(res.success) {
								layer.closeAll();
								layer.msg(res.msg);
								setTimeout(function(){
									location.reload();
								},800)
							} else {
								layer.msg(res.msg);
							}
						})
    		 }) 
						
     
     
     
    	var arr = [];
					//递归获取选中节点的Id
					function getChildrenId(checkData) {
						if(checkData != null) {
							if(checkData.weight!=null){
								arr.push(checkData.id);
								for(var i = 0; checkData.children != null && i < checkData.children.length; i++) {
									getChildrenId(checkData.children[i]);
								}
							}
						}
					}
					
				var b = [];
					//递归获取选中节点的操作id
					function getChildrenId1(checkData) {
						for(var i = 0; checkData.children != null && i < checkData.children.length; i++) {
							b.push(checkData.children[i].id);
						}
					}	
					//判断选中的节点是否在数组a中
					function isInArray(arr,value){
					    for(var i = 0; i < arr.length; i++){
					        if(value === arr[i]){
					            return true;
					        }
					    }
					    return false;
					}

			});
		</script>
		
	</body>
</html>